from svnClient import svnClient
pysvn=__import__('pysvn')
import threading
import os
import time
from icalendar import Calendar, Event, Journal
from datetime import datetime
import string
import commands
from bsddb import db
from subprocess import call
##@author Alessio Di Pietro
#@author Irene Scionti
#@brief methods for writing into the evolution's files 
class pimWriter(object):
    '''
    implemented methods for writing a single entry into the evolution's files  
    '''
    __diff_svnclients=[];
    def __init__(self,settings):
       
      '''
      Constructor
      '''
      self.__diff_sources=[settings.contactspath,settings.icspath,settings.memospath]
    
    ##@brief puts a contact entry into address_book.db
    # @param name_file name of the file to write in evolution's address_book
    # @param path_file path of the directory where the file is
    def berkleyWrite(self,path_file,name_file):
       '''
       this method write the content of name_file, located in the directory indicated by path_file, in the evolution's address_book.db
       '''
      
       
       
       f=open(path_file+name_file,'r')
       #put the content of the file into a string
       string_content=f.read()
       string_content_to_write=string_content.split("(")[0]
      
       #entry's id is the same of name_file, but is necessary to add '\x00' in order to agree on the format of the db
       id=name_file+'\x00'
       contactDB=db.DB()
       contactDB.open( self.__diff_sources[0], None, db.DB_HASH, db.DB_CREATE)
       #put the record in the db
       contactDB.put(id,string_content_to_write)
       contactDB.close();
       # force the shutdown of evolution in order to charge the changes
       os.system("evolution --force-shutdown")
       
    ##@brief writes an event entry in calendar.ics   
    # @param name_file name of the file to write in evolution's calendar.ics, 
    # @param path_file path of the directory where the file is
    def icsWrite(self,path_file,name_file):
       '''
       this method write the content of name_file, located in the directory indicated by path_file, in evolution's calendar.ics
       in this way it is possible to add or restore an event previously deleted 
       '''
       
       f_in=open(path_file+name_file,'r')
       if f_in==None:
           print "error opening ",path_file+name_file;
       else:
           #put the content of the file into a string
           string_content=f_in.readlines()
           length=len(string_content)-1
      
           f_in.close()
           #calendar object contained all the events in calendar.ics
           cal = Calendar.from_string(open(self.__diff_sources[1],'r').read())
           # create an event object_
           event = Event()
      
           i=0;
           # put the informations in string in the new event created before
           #for every read line:
           for line in string_content:
               #operation performed in order to make the line written in the specific syntax of event object
               #split the line in a list of two elements: the first one contains the tag of the field, the second one his value
               string_content_to_write=line.split(":")
               values=string_content_to_write[1].split('\n')
               val=values[0]
               if i!=0 and i<length :
                   #write the tag and his value in the event object
                   event[string_content_to_write[0]] = values[0]
               i=i+1
           #add the new event to the calendar
           cal.add_component(event)
           #open the calendar.ics in write mode
           f_out = open(self.__diff_sources[1], 'w')
           if(f_out==None):
               print "error opening:",self.__diff_sources[1]
           else:
               ##overwrite the cal in calendar.ics with the new one containing the new event 
                f_out.write(cal.as_string())
                f_out.close()
           # force the shutdown of evolution in order to charge the changes
           os.system("evolution --force-shutdown --display=:0")
           
    ##@brief writes a memo entry in journal.ics       
    # @param name_file name of the file to write in evolution's journal.ics, 
    # @param path_file path of the directory where the file is     
    def memosWrite(self,path_file,name_file):
       '''
       this method write the content of name_file, located in the directory indicated by path_file, in evolution's journal.ics
       in this way it is possible to add or restore a memo previously deleted 
       '''
       
       f_in=open(path_file+name_file,'r')
       if f_in==None:
           print "error opening ",path_file+name_file;
       else:
           #put the content of the file into a string
           string_content=f_in.readlines()
           f_in.close()
           length=len(string_content)-1
            #calendar object contained all the memos in journal.ics
           cal = Calendar.from_string(open(self.__diff_sources[2],'r').read())
           # create a journal object_
           journal = Journal()
           i=0;
           # put the informations in string in the new journal created before
           #for every read line:
           for line in string_content:
               #operation performed in order to make the line written in the specific syntax of journal object
               #split the line in a list of two elements: the first one contains the tag of the field, the second one his value
               
               string_content_to_write=line.split(":")
               values=string_content_to_write[1].split('\n')
               if i!=0 and i<length :
               #write the tag and his value in the journal object
                    journal[string_content_to_write[0]] = values[0]
               i=i+1;
           #add the new event to the calendar
           
           cal.add_component(journal)
           
           #open the journal.ics in write mode
           f_out = open(self.__diff_sources[2], 'w')
           if f_out==None:
               print "error opening ",self.__diff_sources[2];
           else:
               #overwrite the cal in journal.ics with the new one containing the new memo 
               f_out.write(cal.as_string())
               f_out.close()
           # force the shutdown of evolution in order to charge the changes
           os.system("evolution --force-shutdown --display=:0")
           
    ##@brief removes a contact entry from address_book.db       
    #@param uid_entry id of the entry to remove
    def contactsRemove(self,uid_entry):
       '''
       remove an existing entry at the current revision from addressbook.db in order to replace with the same entry at another revision
       '''
       #open the db
       contactDB=db.DB()
       contactDB.open( self.__diff_sources[0], None, db.DB_HASH, db.DB_CREATE)
       # getting all the keys 
       array_key=contactDB.keys()
       flag=0;
       #if db is not empty
       if len(array_key)>0:
           #for every key
           for key in array_key:
               #if one key matches with the uid_entry passed to this method
               if key.find(uid_entry)!=-1:
                   #the corresponding record is deleted from the db 
                   contactDB.delete(key)
                   #the flag indicated that the entry was founded and deleted
                   flag=1
           if flag==0:
                print "uid key contact not found"
       contactDB.close();
       # force the shutdown of evolution in order to charge the changes
       os.system("evolution --force-shutdown --display=:0")
    
    ##@brief removes an event entry from calendar.ics    
    #@param uid_entry id of the entry to remove   
    def icsRemove(self,uid_entry):
       '''
       remove an existing entry at the current revision from calendar.ics in order to replace with the same entry at another revision
       '''
       #opening calendar.ics in read mode
       f_in=open(self.__diff_sources[1], 'r')
       if f_in!=None:
           #content of calendar.ics in list
           list=f_in.readlines();
           f_in.close()
           #setting indexes that are used to indicates the lines to delete if the entry is found
           uid_index_first=end_index=-1
           i=0;
           flag=0;
           #for every line of the file
           for line in list:
              #if it's the beginning of an event, the index of the line is saved in begin_index
              if line.find("BEGIN:VEVENT")>-1:
                    begin_index=i;
              #if the id of the entry to remove is found
              if line.find(uid_entry)>-1:
                   # uid_index_first is set to the value of begin_index,  to indicate that the event searched is found
                    uid_index_first=begin_index;
                    #flag set to 1
                    flag=1
              #at the end of the event
              if line.find("END:VEVENT")>-1:
                  #if the uid_index_first and begin_index have the same values, then the entry matches with this event 
                    if uid_index_first==begin_index:
                        #this is the end line of the event. end_index is set to the current line's index
                        end_index=i
                        
              i=i+1;
           #if the entry wasn't found uid_index_first and end_index are set to -1
           #if it was founded index_first and end_index are set to the indexes of the begin and end lines of the corresponding event
           #the lines of the event are removed using index_first and end_index  
           del list[uid_index_first:end_index+1]
          
          #overwriting the calendar.ics with the list of the events
           f_out=open(self.__diff_sources[1], 'w')
           f_out.writelines(list);
           f_out.close()

       
            
           if flag==0:
               print"uid event not found"
       else:
           print "error opening calendar.ics" 
       # force the shutdown of evolution in order to charge the changes 
       os.system("evolution --force-shutdown")
       
    ##@brief removes a memo entry from journal.ics
    #@param uid_entry id of the entry to remove   
    def memosRemove(self,uid_entry):
       '''
       remove an existing entry at the current revision from journal.ics in order to replace with the same entry at another revision
       '''
       #opening journal.ics in read mode
       f_in=open(self.__diff_sources[2], 'r')
       if f_in!=None:
           #content of calendar.ics in list
           list=f_in.readlines();
           f_in.close()
           #setting indexes that are used to indicates the lines to delete if the entry is found
           uid_index_first=end_index=-1
           i=0;
           begin_index=-1
           flag=0;
           #for every line of the file
           for line in list:
              #if it's the beginning of a memo, the index of the line is saved in begin_index
               if line.find("BEGIN:VJOURNAL")>-1:
                    begin_index=i;
               #if the id of the entry to remove is found
               if line.find(uid_entry)>-1:
                   # uid_index_first is set to the value of begin_index to indicate that the memo searched is found 
                    uid_index_first=begin_index;
                    #flag set to 1
                    flag=1;
                    #at the end of the event
               if line.find("END:VJOURNAL")>-1:
                   #if the uid_index_first and begin_index have the same values, then the entry matches with this memo
                    if uid_index_first==begin_index:
                        end_index=i
                    #this is the end line of the memo. end_index is set to the current line's index
                        
               i=i+1;
           #if the entry wasn't found uid_index_first and end_index are set to -1
           #if it was founded index_first and end_index are set to the indexes of the begin and end lines of the corresponding memo
           #the lines of the memo are removed using index_first and end_index  
           
           del list[uid_index_first:end_index+1]
           
           #overwriting the journal.ics with the list of the memos
           f_out=open(self.__diff_sources[2], 'w')
           f_out.writelines(list);
           f_out.close()
       
            
           if flag==0:
               print"uid journal not found"
       else:
           print "error opening journal.ics"  
       # force the shutdown of evolution in order to charge the changes
       os.system("evolution --force-shutdown")